package info.motteke.util.net;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class GetRequest {

    private final String url;

    private final List<Parameter<String>> params;

    private transient String parameterizedUrl = null;

    public GetRequest(String url) {
        this.url = url;
        params = new ArrayList<Parameter<String>>();
    }

    public GetRequest parameter(String key, long value) {
        addParameter(key, Long.toString(value));
        return this;
    }

    @SuppressWarnings("unchecked")
    public GetRequest parameter(String key, Object obj) {
        if (obj instanceof Collection) {
            addAllParameter(key, (Collection<? extends Object>) obj);
        } else if (obj.getClass().isArray()) {
            addAllParameter(key, (Object[]) obj);
        } else {
            addParameter(key, String.valueOf(obj));
        }
        return this;
    }

    /* package */String getUrl() {
        if (parameterizedUrl == null) {
            parameterizedUrl = createUrl();
        }

        return parameterizedUrl;
    }

    private String createUrl() {
        StringBuffer buf = new StringBuffer(url);
        buf.append(getDelimiter());

        for (Parameter<String> param : params) {
            buf.append(param.getKey());
            buf.append('=');
            buf.append(param.getValue());
            buf.append('&');
        }

        buf.deleteCharAt(buf.length() - 1);

        return buf.toString();
    }

    private char getDelimiter() {
        char delimiter;
        if (url.indexOf('?') == -1) {
            delimiter = '?';
        } else {
            delimiter = '&';
        }

        return delimiter;
    }

    private void addParameter(String key, String value) {
        params.add(new Parameter<String>(key, value));
    }

    private void addAllParameter(String key, Collection<? extends Object> collection) {
        for (Object obj : collection) {
            addParameter(key, String.valueOf(obj));
        }
    }

    private void addAllParameter(String key, Object[] array) {
        for (Object obj : array) {
            addParameter(key, String.valueOf(obj));
        }
    }
}
